#include <iostream>
#include <iomanip>
#include <cstring>
#include <string>
#include <string.h>

#include <sys/socket.h>
#include <sys/types.h>
#include <sys/signal.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "my_utils.h"
#include "json.hpp"

int initClient(in_addr_t addr, uint16_t port)
{
    int client;
    struct sockaddr_in client_addr; // 使用结构体 SOCKADDR_IN 存储配置
    client = socket(AF_INET, SOCK_STREAM, 0);

    memset(&client_addr, 0, sizeof(client_addr)); // 清零
    client_addr.sin_family = AF_INET;
    client_addr.sin_addr.s_addr = addr; // server端ip地址
    client_addr.sin_port = port;      // 监听端口

    int res = connect(client, (struct sockaddr *)&client_addr, sizeof(client_addr));

    if (res < 0)
    {
        return -1;
    }
    std::cout << "connection success" << std::endl;
    return client;
}

void setData(int client)
{
    std::string speed, acc, angle, fork;
    std::cin >> speed >> acc >> angle >> fork;

    // 构造请求信息
    nlohmann::json j = {
        {"targetRunValue", std::stof(speed)},
        {"targetRunAccValue", std::stoi(acc)},
        {"targetSpeedValue", std::stof(angle)},
        {"targetForkValue", std::stof(fork)}};

    std::cout << nlohmann::to_string(j) << std::endl;

    std::vector<unsigned char> request = string2Bytes(nlohmann::to_string(j));
    request.insert(request.begin(), 0x00);
    request.insert(request.begin() + 1, 0x00);
    request.insert(request.begin() + 2, 0x32);
    request.push_back(0xff);

    // 发送请求
    unsigned char send_buf[request.size()];
    std::copy(request.begin(), request.end(), send_buf);
    send(client, send_buf, request.size(), 0);

    // 接收响应数据
    unsigned char recv_buf[1024];
    int len = recv(client, recv_buf, 1024, 0);
    if (len > 0)
    {
        std::string str = byte2String(recv_buf, 3, len);
        std::cout << "[response] " << str << std::endl;
    }
}

void askData(int client)
{
    std::vector<unsigned char> request;
    request.push_back(0x00);
    request.push_back(0x00);
    request.push_back(0x3c);
    request.push_back(0xff);

    // 发送请求
    unsigned char send_buf[request.size()];
    std::copy(request.begin(), request.end(), send_buf);
    send(client, send_buf, request.size(), 0);

    // 接收响应数据
    unsigned char recv_buf[1024];
    int len = recv(client, recv_buf, 1024, 0);
    if (len > 0)
    {
        std::string str = byte2String(recv_buf, 3, len);
        std::cout << "[response] " << str << std::endl;
    }
}

int main()
{
    // 初始化socket服务端
    uint16_t port = htons(8181);
    in_addr_t addr = inet_addr("192.168.1.100");

    int client = initClient(addr, port);

    while (true)
    {
        // 获取数据
        askData(client);

        // 发送指令
        setData(client);

        sleep(3);
    }
}